/**
* 下载 获取  blob
* @param  {String} url 目标文件地址
* @return {Promise}
*/
export function getBlob(url, data, mode = 'POST', success, error) {
  const xhr = new XMLHttpRequest();

  xhr.open(mode, url, true);

  // 监听进度事件
  xhr.addEventListener(
    "progress",
    function (evt) {
      let percentage = 0
      if (evt.lengthComputable) {
        let percentComplete = evt.loaded / evt.total;
        percentage = Math.floor(percentComplete * 100 * 100) / 100;
      }
      if (evt.total == 0) {
        percentage = 100
      }
      success(percentage)
    },
    false
  );

  xhr.responseType = "blob";
  xhr.onload = () => {
    let fileReader = new FileReader();
    fileReader.onload = function () {
      try {
        let jsonData = JSON.parse(this.result); // 说明是普通对象数据，后台转换失败
        if (jsonData.code !== 1) {
          // Message.error(jsonData.msg);
          error(jsonData.msg)
        }
      } catch (err) {
        if (xhr.status === 200) {
          let str = xhr.getResponseHeader("content-disposition")
          let fileName = '文件下载'
          if (str) {
            let newname = str.split("filename=")[1];
            fileName = decodeURIComponent(newname.split(".")[0]) + '.' + newname.split(".")[1];
          }
          saveAs(xhr.response, fileName);
        } else {
          // Message.error(err);
          error(err)
        }
      }
    }
    fileReader.readAsText(xhr.response)
  };

  xhr.send(data);
}

/**
* 保存
* @param  {Blob} blob
* @param  {String} filename 想要保存的文件名称
*/
export function saveAs(blob, filename) {
  // ie的下载
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    // 非ie的下载
    const link = document.createElement("a");
    const body = document.querySelector("body");

    link.href = window.URL.createObjectURL(blob);
    link.download = filename;

    // fix Firefox
    link.style.display = "none";
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}
